package com.atdfrz.secondshop.controller.user;

import com.atdfrz.secondshop.dto.CartDto;
import com.atdfrz.secondshop.dto.LayuiResult;
import com.atdfrz.secondshop.mapper.*;
import com.atdfrz.secondshop.pojo.*;
import com.atdfrz.secondshop.service.IAddressService;
import com.atdfrz.secondshop.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class OrderController extends BaseController{
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 跳转到订单页面
     * @return
     */
    @RequestMapping("/front/order")
    public String toorder(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/order";
    }
    /**
     * 在查看商品详情页，点击立即购买，跳转到订单页面
     * @return
     */
    @RequestMapping("/front/orderNow")
    public String orderNow(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/orderNow";
    }

    /**
     * 查看历史订单页面
     * @return
     */
    @RequestMapping("/front/myorderq")
    public String tomyorderq(HttpSession session,Model model) {
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        //根据订单创建时间和修改时间降序排
        wrapper.eq(Order::getUserId,userid).orderByDesc(Order::getCreateTime).orderByDesc(Order::getUpdateTime);
        List<Order> orders = orderMapper.selectList(wrapper);
        //查询所有订单并根据订单创建时间和修改时间降序排
        model.addAttribute("orders",orders);
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);

//        //给orders里封装的每个orderDetail赋值
//        List<Order> detailOrders=orders.stream().map((item)->{
//
//        }).collect(Collectors.toList());
//
//        for (Order order : orders) {
//            Order orderAndItembyOrderId = orderMapper.findOrderAndItembyOrderId(order.getOrderId());
//        }
        return "/front/myorderq";
    }

    //在历史订单页面中点击订单详情进行查看
    @RequestMapping("/front/orderxq")
    public String toorderxq(Model model){
        List<Category> category = categoryMapper.selectList(null);
        model.addAttribute("category",category);
        return "/front/orderxq";
    }
    //在历史订单页面中点击订单详情进行查看
    @RequestMapping("/front/searchOrderxq")
    @ResponseBody
    public LayuiResult searchOrderxq(@RequestBody Order order, Model model, HttpSession session){
        Long orderId = order.getOrderId();
//        List<Order> orderList = orderMapper.findOrderAndItembysOrderId(orderId);
        Order orderAndItem = orderMapper.findOrderAndItembyOrderId(orderId);
        Order orderinfo = orderMapper.selectById(orderId);
        LayuiResult<Object> result = new LayuiResult<>();
        if (orderAndItem!=null){
            session.setAttribute("orderId",orderId);
            session.setAttribute("orderAndItem",orderAndItem);
            session.setAttribute("orderinfo",orderinfo);
            result.setCode(1);
            result.setMessage("订单详情");
            return result;
        }
        result.setCode(2);
        result.setMessage("订单详情失败");
        return result;

    }

    /**
     *根据选中的购物车id查询详情列表信息
     * 订单确认界面
     * @return
     */
    @PostMapping("/front/confirmOrder")
    @ResponseBody
    public LayuiResult confirmOrder(@RequestBody Integer[] cartIds, HttpSession session, Model model){
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        //根据购物车中选中的购物车id跳转到订单确认页面
        List<CartDto> cartDtos = cartMapper.findCartDtoByCartIds(cartIds);
        model.addAttribute("cartDtos", cartDtos);
        session.setAttribute("cartDtos", cartDtos);
        session.setAttribute("cartIds", cartIds);
        //计算选中的购物车商品的总价格
        Integer totalPrice = 0;
        for (CartDto cartDto : cartDtos) {
            totalPrice += cartDto.getProducPrice() * cartDto.getQuantity();
        }
        //把选中的商品价格计算并保存到session中
        session.setAttribute("totalPrice", totalPrice);
        //根据userid获取user的地址
        List<Address> userAddress = addressService.getByUserid(userid);
        for (Address userDefuAddress : userAddress) {
            //遍历用户的所有收货地址，如果是默认地址的话，则保存到model里面
            Integer defaultAddress = userDefuAddress.getIsDefault();
            if (defaultAddress == 1) {
                model.addAttribute("userDefuAddress", userDefuAddress);
                session.setAttribute("userDefuAddress", userDefuAddress);
            }
        }
        Address address = (Address) session.getAttribute("userDefuAddress");
        LayuiResult<Object> result = new LayuiResult<>();
        if (address == null) {
            result.setCode(3);
            result.setMessage("请先去一个设置默认地址噢");
            return result;
        }
        if (cartDtos != null && address != null) {
            result.setCode(1);
            result.setMessage("欢迎来到订单确认页面");
            return result;
        } else {
            result.setCode(0);
            result.setMessage("订单信息有误");
            return result;
        }

    }

    /**
     *在查看订单确认页面点击立即支付：
     * 订单确认界面,0(用户取消订单);1(未付款);2(已付款);3(已发货);4(交易完成);
     * @return
     */
    @Transactional
    @PostMapping("/front/createOrder")
    @ResponseBody
    public LayuiResult createOrder(HttpSession session, Model model) {
        LayuiResult<Object> result = new LayuiResult<>();
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        //获取session中保存的购物车商品项数据
        List<CartDto> cartDtos = (List<CartDto>) session.getAttribute("cartDtos");
        //获取session中用户保存的默认地址作为订单的
        Address address = (Address) session.getAttribute("userDefuAddress");
        Integer totalPrice = (Integer) session.getAttribute("totalPrice");
        long orderId = IdWorker.getId();
        //将新创建的订单id保存在session中
        session.setAttribute("newOrderId",orderId);
        Order order = new Order();
        //设置订单的id
        order.setOrderId(orderId);
        //收货地址相关的6项
        order.setReceiverName(address.getUsername());
        order.setReceiverPhone(address.getPhone());
        order.setReceiverAddress(address.getAddress());
        order.setReceiverArea(address.getAreaName());
        order.setReceiverProvince(address.getProvinceName());
        order.setReceiverCity(address.getCityName());
        //设置订单的userid
        order.setUserId(userid);
        //设置订单状态：0(用户取消订单);1(未付款);2(已付款);3(已发货);4(交易完成);
        order.setStatus(1);
        //下单时间
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //设置订单的总金额
        order.setTotalPrice(totalPrice);
        //插入进订单表
        int insert = orderMapper.insert(order);

        // 遍历选中的购物车项，循环插入订单商品数据
        for (CartDto cartDto : cartDtos) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setProductId(cartDto.getProductId());
            orderDetail.setProductName(cartDto.getProductName());
            orderDetail.setProductPhoto(cartDto.getProducPhoto());
            //设置订单详情中各项商品的数量
            orderDetail.setQuantity(cartDto.getQuantity());
            //设置订单详情表中各个订单的单价
            orderDetail.setUnitPrice(cartDto.getProducPrice());
            orderDetail.setTotalPrice(cartDto.getProducPrice()*cartDto.getQuantity());
            orderDetail.setCreateTime(new Date());
            orderDetail.setUpdateTime(new Date());
            int insertorderDetail = orderDetailMapper.insert(orderDetail);
            if (insertorderDetail != 0 && insert != 0) {
                result.setCode(1);
                result.setMessage("插入成功");
            }
            //更新商品的库存和销量
            Product product = productMapper.selectById(cartDto.getProductId());
            product.setAmount(product.getAmount()-cartDto.getQuantity());
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.eq(Product::getProductId,product.getProductId());
            productMapper.update(product,productWrapper);
//            //删除被选中的购物车中的商品
//            LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
//            wrapper.eq(Cart::getCartId,cartDto.getCartId());
//            cartMapper.deleteById(wrapper);
        }
        //删除选中的购物车中的商品数据
        Integer[] arr=(Integer[])session.getAttribute("cartIds");
       cartMapper.deleteBatchIds(Arrays.asList(arr));

        return result;
    }

    /**
     * 在订单支付页面完成支付,订单状态：0(用户取消订单);1(未付款);2(已付款,未发货);3(已发货);4(交易完成);
     * 则将订单状态设为2
     * @return
     */
    @PostMapping("/front/finishPay")
    @ResponseBody
    public LayuiResult finishPay(HttpSession session, Model model){
        LayuiResult<Object> result = new LayuiResult<>();
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        Long orderId=(Long) session.getAttribute("newOrderId");
        Order order = orderMapper.selectById(orderId);
        //将订单状态设为2，表示已付款
        order.setStatus(2);
        order.setUpdateTime(new Date());
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>();
        wrapper.eq(Order::getOrderId,orderId);
        int update = orderMapper.update(order, wrapper);
        if (update>0){
            result.setCode(1);
            result.setMessage("付款成功");
            return result;
        }else {
            result.setCode(2);
            result.setMessage("付款失败");
            return result;
        }
    }

    /**
     * 在我的所有订单页面选择待支付的订单点击去支付：0(用户取消订单);1(未付款);2(已付款,未发货);3(已发货);4(交易完成);
     * 则将订单状态设为2
     * @return
     */
    @PostMapping("/front/toPay")
    @ResponseBody
    public LayuiResult toPay(@RequestBody Order order,HttpSession session){
        LayuiResult<Object> result = new LayuiResult<>();
        if (order!=null){
            Long newOrderId = order.getOrderId();
            session.setAttribute("newOrderId",newOrderId);
            result.setCode(1);
            result.setMessage("即将去付款");
            return result;
        }
        result.setCode(2);
        result.setMessage("状态异常");
        return result;

    }


    /**
     * 在订单页面点击确认收货,订单状态：0(用户取消订单);1(未付款);2(已付款,未发货);3(已发货,等待收货);4(确认收货，交易完成);
     * 则将订单状态修改为4
     * @return
     */
    @PostMapping("/front/confirmReceive")
    @ResponseBody
    public LayuiResult confirmReceive(@RequestBody Order order, HttpSession session){
        Order order1 = orderMapper.selectById(order.getOrderId());
        order1.setStatus(4);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderId,order.getOrderId());
        LayuiResult<Object> result = new LayuiResult<>();
        int update = orderMapper.update(order1, wrapper);
        if (update>0){
            result.setCode(1);
            result.setMessage("确认收货成功");
            return result;
        }else {
            result.setCode(2);
            result.setMessage("确认收货失败");
            return result;
        }
    }

    /**
     *在查看商品详情页面，点击立即购买(后会跳转到订单确认的页面)
     */
    @PostMapping("/front/buyNow")
    @ResponseBody
    public LayuiResult buyNow(@RequestBody Product product,HttpSession session,Model model){
        //获取登录时保存的用户session对象
        Integer userid = getUidFromSession(session);
        Integer productId = product.getProductId();
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        Product product1 = productMapper.selectById(productId);
        product1.setQuantity(product.getQuantity());
        session.setAttribute("product1",product1);
        List<Address> userAddress = addressService.getByUserid(userid);
        for (Address userDefuAddress : userAddress) {
            //遍历用户的所有收货地址，如果是默认地址的话，则保存到model里面
            Integer defaultAddress = userDefuAddress.getIsDefault();
            if (defaultAddress == 1) {
                model.addAttribute("userDefuAddress", userDefuAddress);
                session.setAttribute("userDefuAddress", userDefuAddress);
            }
        }
        Address address = (Address) session.getAttribute("userDefuAddress");
        LayuiResult<Object> result = new LayuiResult<>();
        if (address == null) {
            result.setCode(3);
            result.setMessage("请先去一个设置默认地址噢");
            return result;
        }
        if (address != null &&product1!=null) {
            result.setCode(1);
            result.setMessage("欢迎来到订单确认页面");
            return result;
        }else{
            result.setCode(2);
            result.setMessage("信息有误");
            return result;
        }

    }

    /**
     *在查看订单确认页面点击立即支付：
     * 订单确认界面,0(用户取消订单);1(未付款);2(已付款);3(已发货);4(交易完成);
     * @return
     */
    @Transactional
    @PostMapping("/front/createOrderBuyNow")
    @ResponseBody
    public LayuiResult createOrderBuyNow(HttpSession session, Model mode){
        LayuiResult<Object> result = new LayuiResult<>();
        //获取登陆保存的session信息
        Integer userid = getUidFromSession(session);
        //获取session中用户保存的默认地址作为订单的
        Address address = (Address) session.getAttribute("userDefuAddress");
        //获取session中用户保存的商品信息
        Product product=(Product) session.getAttribute("product1");
        Integer totalPrice =product.getQuantity()*product.getPrice();
        long orderId = IdWorker.getId();
        //将新创建的订单id保存在session中
        session.setAttribute("newOrderId",orderId);
        Order order = new Order();
        //设置订单的id
        order.setOrderId(orderId);
        //收货地址相关的6项
        order.setReceiverName(address.getUsername());
        order.setReceiverPhone(address.getPhone());
        order.setReceiverAddress(address.getAddress());
        order.setReceiverArea(address.getAreaName());
        order.setReceiverProvince(address.getProvinceName());
        order.setReceiverCity(address.getCityName());
        //设置订单的userid
        order.setUserId(userid);
        //设置订单状态：0(用户取消订单);1(未付款);2(已付款);3(已发货);4(交易完成);
        order.setStatus(1);
        //下单时间
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //设置订单的总金额
        order.setTotalPrice(totalPrice);
        //插入一条数据进订单表
        int insert = orderMapper.insert(order);

        //插入一条数据进订单详情表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(orderId);
        orderDetail.setProductId(product.getProductId());
        orderDetail.setProductName(product.getName());
        orderDetail.setProductPhoto(product.getPhoto());
        //设置订单详情中各项商品的数量
        orderDetail.setQuantity(product.getQuantity());
        //设置订单详情表中各个订单的单价
        orderDetail.setUnitPrice(product.getPrice());
        orderDetail.setTotalPrice(product.getPrice()*product.getQuantity());
        orderDetail.setCreateTime(new Date());
        orderDetail.setUpdateTime(new Date());
        int insertorderDetail = orderDetailMapper.insert(orderDetail);
        if (insertorderDetail != 0 && insert != 0) {
            result.setCode(1);
            result.setMessage("插入成功");
        }
        //更新商品的库存和销量
        Product product1 = productMapper.selectById(product.getProductId());
        product1.setAmount(product1.getAmount()-product.getQuantity());
        LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
        productWrapper.eq(Product::getProductId,product1.getProductId());
        productMapper.update(product1,productWrapper);
        return result;
    }

    /**
     * 在个人中心，显示待支付、待收货、待评价的订单数
     */
    @PostMapping("/front/showCountOrderStatus")
    @ResponseBody
    public LayuiResult createOrde(HttpSession session,Model model,Integer status){
        LayuiResult<Object> result = new LayuiResult<>();
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,1).eq(Order::getStatus,status);
        long count = orderService.count(wrapper);
        if (count!=0){
            result.setCode(1);
            result.setMessage("查询成功");
            result.setData(count);
        }
        return result;
    }

}
